<template>
  <BasicModal
    width="400px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    okText="保存"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <BasicTree
      v-if="menuList.length"
      title="菜单列表"
      checkable
      toolbar
      search
      v-model:value="menuSelectedRowKeys"
      :clickRowToExpand="false"
      :treeData="menuList"
      :fieldNames="{ key: 'id', title: 'menuTitle' }"
      :defaultExpandAll="true"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    bindPermissionMenuRelation,
    queryMenuCheckedTreeListOfPermissionId,
  } from '/@/api/system/system';
  import { apiColumns } from '/@/views/system/permission/permission.data';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { PermissionMenuReq } from '/@/api/system/modal/permissionMenuModel';
  import { MenuResp } from '/@/api/system/modal/menuModel';

  export default defineComponent({
    name: 'PermissionMenuApiModal',
    components: {
      BasicTree,
      BasicModal,
    },
    emits: ['success', 'register', 'cancel'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const id = ref('');
      const loading = ref(false);

      const menuSelectedRowKeys = ref<string[]>([]);
      const menuList = ref<MenuResp[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;

        if (data?.record && data?.record?.id) {
          const permissionMenuReq: PermissionMenuReq = {
            permissionId: data?.record?.id,
          };
          menuList.value = await queryMenuCheckedTreeListOfPermissionId(permissionMenuReq);
        } else {
          menuList.value = (await queryMenuCheckedTreeListOfPermissionId()) as any as TreeItem[];
        }

        if (menuList.value && menuList.value.length > 0) {
          getTreeSelectRowKeys(menuList.value);
        }
      });

      const getTitle = computed(() => '授权菜单');

      watch(
        () => id,
        () => {
          menuSelectedRowKeys.value = [];
        },
        { deep: true },
      );

      function getTreeSelectRowKeys(menuList: MenuResp[]) {
        for (const menuResp of menuList) {
          if (menuResp.checked === true && menuResp.id) {
            menuSelectedRowKeys.value.push(menuResp.id);
          }
          if (menuResp && menuResp.children && menuResp.children.length > 0) {
            getTreeSelectRowKeys(menuResp.children);
          }
        }
      }

      async function handleSubmit() {
        try {
          const permissionMenuReq: PermissionMenuReq = {
            permissionId: unref(id),
            menuIds: unref(menuSelectedRowKeys),
          };
          await bindPermissionMenuRelation(permissionMenuReq);
          closeModal();
          createMessage.success('保存成功');
          emit('success', {
            isUpdate: unref(isUpdate),
            values: { menuIds: unref(menuSelectedRowKeys), id: unref(id) },
          });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function handleCancel() {
        emit('cancel');
      }

      return {
        apiColumns,
        permissionId: id,
        registerModal,
        getTitle,
        loading,
        menuList,
        menuSelectedRowKeys,
        handleSubmit,
        handleCancel,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 3px;
    height: 0px;
  }

  ::-webkit-scrollbar-track-piece {
    background-color: rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:vertical {
    height: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:horizontal {
    width: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }
</style>
